package com.wydexcel.generate.process;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class ExcelCommonProcess {


    private final Workbook workbook;

    public ExcelCommonProcess(Workbook workbook) {
        this.workbook = workbook;
    }


    private Map<String, Sheet> map = new HashMap<>();

    public Sheet getSheet(String sheetName) {
        Sheet sheet = map.get(sheetName);
        if (null == sheet) {
            sheet = workbook.createSheet(sheetName);
            map.put(sheetName, sheet);
        }

        return sheet;
    }

    private Map<Integer, Integer> rowMap = new HashMap<>();

    public Row getRow(String sheetName, int index) {
        Sheet sheet = getSheet(sheetName);
        Integer row = rowMap.get(index);
        if (null == row) {
            Row createRow = sheet.createRow(index);
            rowMap.put(index, index);
            return createRow;
        }
        return sheet.getRow(index);
    }


    public Cell getCell(Row row, int cellIndex) {
        return row.createCell(cellIndex);
    }


    public void write(OutputStream outputStream) throws IOException {
        this.workbook.write(outputStream);
    }

    public boolean write(String path) {
        try {
            write(new FileOutputStream(new File(path)));
            return true;
        } catch (Exception e) {
            return false;
        }
    }


}
